package org.footballmanager.pandafootball.common.util;

import lombok.extern.slf4j.Slf4j;
import org.footballmanager.pandafootball.common.exception.ExceptionEnum;
import org.footballmanager.pandafootball.common.exception.MyException;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author CXY
 */
@Slf4j
public class MD5Encoder {
    private MD5Encoder(){}

	/**
	 * 把字节数组转成16进位制数
	 * @param bytes
	 * @return
	 */
	public static String bytesToHex(byte[] bytes) {
		StringBuilder md5str = new StringBuilder();
		//把数组每一字节换成16进制连成md5字符串
		int digital;
		for (int i = 0; i < bytes.length; i++) {
			 digital = bytes[i];
			if(digital < 0) {
				digital += 256;
			}
			if(digital < 16){
				md5str.append("0");
			}
			md5str.append(Integer.toHexString(digital));
		}
		return md5str.toString().toUpperCase();
	}
	
	/**
	 * 把字节数组转换成md5
	 * @param input
	 * @return
	 */
	public static String bytesToMD5(byte[] input) {
        //创建一个提供信息摘要算法的对象,初始化为md5算法对象
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new MyException(ExceptionEnum.NOSUCHALGORITHMEXCEPTION, e);
        }
        //计算后获得字节数组
        byte[] buff = md.digest(input);
        //把数组每一字节换成16进制连成md5字符串
        return bytesToHex(buff);
	}
	/**
	 * 把字符串转换成md5
	 * @param str
	 * @return
	 */
	public static String strToMD5(String str) {
		byte[] input = str.getBytes();
		return bytesToMD5(input);
	}
	
}